<template>
  <div class="detail-page">
    <el-card shadow="hover">
      <el-descriptions :column="2" border v-loading="loading || loadingOptions"> <!-- 添加 loadingOptions -->
        <el-descriptions-item label="序号">{{ customer.id }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">
          <el-input v-if="isEditing" v-model="customer.name"></el-input>
          <span v-else>{{ customer.name }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-select
            v-if="isEditing"
            v-model="customer.type"
            placeholder="客户类别"
            size="large"
            style="width: 240px"
            :loading="loadingOptions"
          >
            <el-option
              v-for="item in data.type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ getTypeName(customer.type) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="地址">
          <div style="display: flex; gap: 10px;">
            <el-select
              v-if="isEditing"
              v-model="customer.province"
              placeholder="请选择省份"
              style="width: 80px"
              @change="onProvinceChange"
            >
              <el-option
                v-for="(cities, province) in provinces"
                :key="province"
                :label="province"
                :value="province"
              />
            </el-select>
            <el-select
              v-if="isEditing"
              v-model="customer.city"
              placeholder="请选择城市"
              style="width: 80px"
              :disabled="!customer.province"
              @change="onCityChange"
            >
              <el-option
                v-for="city in currentCities"
                :key="city"
                :label="city"
                :value="city"
              />
            </el-select>
            <el-select
              v-if="isEditing"
              v-model="customer.district"
              placeholder="请选择区县"
              style="width: 80px"
              :disabled="!customer.city"
            >
              <el-option
                v-for="district in currentDistricts"
                :key="district"
                :label="district"
                :value="district"
              />
            </el-select>
            <span v-else>{{ customer.address }}</span>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="客户来源">
          <el-select
            v-if="isEditing"
            v-model="customer.source"
            placeholder="客户来源"
            size="large"
            style="width: 240px"
            :loading="loadingOptions"
          >
            <el-option
              v-for="item in data.source_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span v-else>{{ getSourceName(customer.source) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="电话">
          <el-input
            v-if="isEditing"
            v-model="customer.phone"
            :maxlength="11"
            @input="filterPhoneNumber"
          ></el-input>
          <span v-else>{{ customer.phone }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(customer.status)">
            {{ getStatusText(customer.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下次联系时间">
          <el-date-picker
            v-if="isEditing"
            v-model="customer.next_time"
            type="datetime"
          ></el-date-picker>
          <span v-else>{{ customer.next_time }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="跟进时间">
          <span>{{ customer.follow_time}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="进入公海时间">
          <el-date-picker
            v-if="isEditing"
            v-model="customer.seas_time"
            type="datetime"
          ></el-date-picker>
          <span v-else>{{ customer.seas_time }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          <el-input
            v-if="isEditing"
            v-model="customer.explain"
            type="textarea"
          ></el-input>
          <span v-else>{{ customer.explain }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <div class="action-buttons">
        <el-button v-if="!isEditing" type="primary" @click="toggleEdit">修改</el-button>
        <template v-if="isEditing">
          <el-button type="success" @click="saveChanges">保存</el-button>
          <el-button type="warning" @click="cancelEdit">取消</el-button>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRoute } from "vue-router";
import {
  Get_Customer_Details,
  Update_Customer_Details,
} from "@/api/customer/index";
import type { Customer_Detail_Data } from "@/utils/types";
import dayjs from "dayjs";
import { Get_Origin, Get_Type } from "@/api/customer/index";
import { notice } from "@/utils/notice";
import cities from "@/components/CustomerVip/cities.json";
import { ElMessage } from "element-plus";

const route = useRoute();
const emit = defineEmits(["myclose"]);

const customer = ref<Customer_Detail_Data>({
  id: "",
  name: "",
  type: "",
  address: "",
  source: "",
  phone: "",
  level: "",
  status: 0,
  next_time: "",
  follow_time: "",
  seas_time: "",
  explain: "",
  province: "",
  city: "",
  district: "",
});

const originalCustomer = ref<Customer_Detail_Data>({
  ...customer.value
});

const data = reactive({
  isFirst: true,
  source_list: [] as Array<{ id: string; name: string }>,
  type_list: [] as Array<{ id: string; name: string }>,
});

const loading = ref(true);
const isEditing = ref(false);
const loadingOptions = ref(false);
const props = defineProps(["data"]);

const provinces = ref(cities);
const currentCities = ref<string[]>([]);
const currentDistricts = ref<string[]>([]);

// 封装获取选项数据的函数
const fetchOptionsData = async () => {
  if (data.source_list.length > 0 && data.type_list.length > 0) {
    return;
  }
  loadingOptions.value = true;
  try {
    const [res, res1] = await Promise.all([
      Get_Origin({ keys: ["customer_source"] }),
      Get_Type({ keys: ["origin"] }),
    ]);
    if (res.code === 0) {
      data.source_list = res.data.data;
    }
    if (res1.code === 0) {
      data.type_list = res1.data.data;
    }
  } catch (error) {
    console.error("获取选项数据失败", error);
    ElMessage.error("获取选项数据失败，请稍后重试");
  } finally {
    loadingOptions.value = false;
  }
};

onMounted(async () => {
  try {
    await fetchOptionsData();
    const res = await Get_Customer_Details({
      id: props.data,
    });
    if (res.code === 0) {
      customer.value = res.data.data[0];
      originalCustomer.value = { ...res.data.data[0] };
      const addressParts = customer.value.address.split('/');
      if (addressParts.length === 3) {
        customer.value.province = addressParts[0];
        customer.value.city = addressParts[1];
        customer.value.district = addressParts[2];
        // 确保初始化时正确更新市与区的选项
        currentCities.value = Object.keys(provinces.value[customer.value.province] || {});
        const currentCity = customer.value.city;
        currentDistricts.value = provinces.value[customer.value.province]?.[currentCity] || [];
      }
    }
  } catch (error) {
    ElMessage.error("获取客户详情失败，请稍后重试");
  } finally {
    loading.value = false;
  }
});

const onProvinceChange = (province: string) => {
  currentCities.value = Object.keys(provinces.value[province] || {});
  customer.value.city = "";
  customer.value.district = "";
  currentDistricts.value = [];
};

const onCityChange = (city: string) => {
  currentDistricts.value = provinces.value[customer.value.province]?.[city] || [];
  customer.value.district = "";
};

const getSourceName = (sourceId: string) => {
  console.log('sourceId:', sourceId); // 调试用，查看传入的 sourceId
  console.log('data.source_list:', data.source_list); // 调试用，查看 source_list 数据
  const source = data.source_list.find(item => item.id === sourceId);
  return source ? source.name : '';
};

const toggleEdit = async () => {
  loadingOptions.value = true; // 开始加载动画
  try {
    const res = await Get_Origin({
      keys: ["customer_source"],
    });
    if (res.code === 0) {
      data.source_list = res.data.data;
    }

    const res1 = await Get_Type({
      keys: ["origin"],
    });
    if (res1.code === 0) {
      data.type_list = res1.data.data;
    }

    isEditing.value = !isEditing.value;
  } catch (error) {
    console.error("获取选项数据失败", error);
  } finally {
    loadingOptions.value = false; // 结束加载动画
  }
};

const saveChanges = async () => {
  // 验证必填字段
  const { name, phone, type, source, province, city, district } = customer.value;
  if (!name || !phone || !type || !source || !province || !city || !district) {
    alert('请确保所有必填字段都已填写！');
    return;
  }
  customer.value.address = `${province}/${city}/${district}`;

  loading.value = true;
  try {
    const res = await Update_Customer_Details({
      id: customer.value.id,
      name: customer.value.name,
      type: customer.value.type,
      address: customer.value.address,
      source: customer.value.source,
      phone: customer.value.phone,
      next_time: customer.value.next_time,
      seas_time: customer.value.seas_time,
      explain: customer.value.explain,
    });
    if (res.code === 0) {
      isEditing.value = false;
      notice({ code: 0, message: "客户信息更新成功" });
      originalCustomer.value = { ...customer.value }; // 更新原始数据

    } else {
      notice(res);
    }
  } catch (error) {
    console.error("更新客户信息失败", error);
    notice({ code: -1, message: "更新客户信息失败" });
  } finally {
    loading.value = false;
  }
};

const cancelEdit = () => {
  // 恢复原始数据
  customer.value = { ...originalCustomer.value };
  isEditing.value = false;
};

const formatTime = (time: string) => {
  return time ? dayjs(time).format("YYYY-MM-DD HH:mm:ss") : "-";
};

const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return "primary";
    case 2:
      return "success";
    default:
      return "warning";
  }
};

const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return "进行中";
    case 2:
      return "已转化";
    default:
      return "公海";
  }
};

const getTypeName = (typeId: string) => {
  const type = data.type_list.find(item => item.id === typeId);
  return type ? type.name : '';
};




const filterPhoneNumber = (value: string) => {
  customer.value.phone = value.replace(/\D/g, '');
};
</script>

<style scoped>
.detail-page {
  /* padding: 20px; */
}

.el-card {
  /* margin-top: 20px; */
  padding: 20px;
}

.el-descriptions {
  margin-top: 20px;
}

.el-descriptions .el-descriptions__body .el-descriptions__cell {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 48px; /* 设置固定高度 */
}

.el-descriptions
  .el-descriptions__body
  .el-descriptions__cell
  .el-descriptions__label {
  font-weight: bold;
  width: 150px; /* 固定标签宽度 */
}

.el-descriptions
  .el-descriptions__body
  .el-descriptions__cell
  .el-descriptions__content {
  flex-grow: 1;
  text-align: left;
}

.action-buttons {
  margin-top: 20px;
  text-align: right;
}
</style>
